import Auth from './permission/index'
import { usePermissionStore } from '@/store'
import { uploads } from '@/service'
/**
 * 相册摄像权限校验
 */
async function auths() {
  const store = usePermissionStore()
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    let authState = 0
    // #ifdef MP
    authState += await new Auth('writePhotosAlbum').check()
    if (authState < 1) return
    authState += await new Auth('camera').check()
    if (authState < 2) return
    // #endif
    // #ifdef APP
    authState += (await store.requestPermissions('writePhotosAlbum')) as number
    if (authState < 1) return
    authState += (await store.requestPermissions('camera')) as number
    if (authState < 2) return
    // #endif
    resolve(true)
  })
}

/**
 * 上传图片
 */
export const _uploadImg = async (count = 9) => {
  await auths()
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 从相册选择
      success: async (res) => {
        uni.showLoading({
          title: '上传中...',
        })
        resolve(await uploads(res.tempFilePaths[0]))
      },
    })
  })
}
/**
 * 上传视频
 */
export const _uploadVideo = (url, name, type) => {
  auths()
  return new Promise((resolve, reject) => {
    uni.chooseVideo({
      sourceType: ['camera', 'album'],
      success: async (res) => {
        if (res.tempFile.size >= 10 * 1024 * 1024) {
          uni.$uv.toast('视频不能大于10M')
          reject(new Error('视频不能大于10M'))
          return
        }
        resolve(await uploads(res.tempFilePath))
      },
    })
  })
}
/**
 * 上传文件 仅支持H5 、 微信 、 QQ
 */
export const _uploadFile = () => {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    uni.chooseFile({
      count: 1,
      extension: ['.text', '.pdf', '.doc', '.docx', '.xls'],
      success: async (res) => {
        resolve(await uploads(res.tempFiles[0].path))
      },
    })
    // #endif
    // #ifdef MP-WEIXIN | MP-QQ
    wx.chooseMessageFile({
      count: 1,
      success: async (res) => {
        if (res.tempFiles[0].type !== 'file') {
          uni.$uv.toast('该文件类型不支持')
          return reject(new Error('该文件类型不支持'))
        }
        resolve(await uploads(res.tempFiles[0].path))
      },
    })
    // #endif
  })
}
/**
 * 文件下载
 * @param url 文件路径
 * @param fileName 文件名
 */
export class downFile {
  url: string
  fileName: string
  constructor(url: string, fileName: string) {
    this.url = url
    this.fileName = fileName
  }

  async down() {
    // #ifdef APP
    const store = usePermissionStore()
    const aut = (await store.requestPermissions('writePhotosAlbum')) as number
    if (aut !== 1) return
    // #endif
    uni.showLoading({
      title: '正在下载，请稍等...',
      mask: true,
    })
    const downloadTask = await this.netDownFile()
    if (!downloadTask) {
      uni.$uv.toast('下载失败，请稍后再试')
      return uni.hideLoading()
    }
    if (this.isImg()) {
      // 图片保存到手机相册
      uni.saveImageToPhotosAlbum({
        filePath: downloadTask,
        success: function () {
          uni.$uv.toast('文件下载成功')
        },
        fail: function () {
          uni.$uv.toast('文件下载失败')
        },
      })
    } else if (this.isVideo()) {
      // 保存视频到相册
      uni.saveVideoToPhotosAlbum({
        filePath: downloadTask,
        success: function () {
          uni.$uv.toast('文件下载成功')
        },
        fail: function () {
          uni.$uv.toast('文件下载失败')
        },
      })
    } else {
      // #ifdef APP-PLUS
      const osname = plus.os.name
      uni.saveFile({
        tempFilePath: downloadTask,
        success: (res) => {
          if (osname === 'Android') {
            // 原来的文件名
            const newFileName = this.url.split('/')[this.url.split('/').length - 1]
            const sFileName = this.fileName + '.' + newFileName.split('.')[1]
            this.fSetFileName(sFileName)
          } else {
            uni.openDocument({
              filePath: res.savedFilePath,
            })
          }
        },
      })
      // #endif
      // #ifdef MP-WEIXIN
      const FileSystemManager = wx.getFileSystemManager()
      FileSystemManager.saveFile({
        tempFilePath: downloadTask,
        success: (res) => {
          if (res.errMsg !== 'saveFile:ok') {
            uni.showToast({
              title: '文件保存失败',
            })
            return
          }
          if (uni.getSystemInfoSync().platform === 'android') {
            uni.showModal({
              title: '保存地址为',
              content: '手机存储/Android/data/com.tencent.mm/MicroMsg/wxanewfiles',
            })
          } else {
            uni.showToast({
              title: '抱歉IOS暂不支持',
              icon: 'none',
            })
          }
        },
      })
      // #endif
      // #ifdef H5
      const createA = document.createElement('a')
      createA.download = this.fileName
      createA.href = this.url
      document.body.appendChild(createA)
      createA.click()
      createA.remove()
      // #endif
    }
    uni.hideLoading()
  }

  /**
   * 文件下载
   */
  netDownFile(): Promise<string> {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url: this.url,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.tempFilePath)
          } else {
            uni.showToast({
              title: '文件下载失败',
            })
            reject(new Error(''))
          }
        },
      })
    })
  }

  /**
   * APP文件保存重命名
   * @param {Object} sFileName 文件名
   */
  fSetFileName(sFileName: string) {
    // saveFile API保存的本地地址
    const url = this.url // 下载地址
    const ZH = import.meta.env.VITE_APP_TITLE
    const dtask = plus.downloader.createDownload(
      url,
      {
        // 在手机存储更目录创建一个本应用的文件夹，把文件存储进去，并更改会原名
        filename: `file://storage/emulated/0/${ZH}/${sFileName}`,
      },
      (d, status) => {
        if (status === 200) {
          const fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename)
          uni.$uv.toast(`已保存到文件夹：/${ZH}/${sFileName}`)
          setTimeout(() => {
            plus.runtime.openFile(d.filename) // 选择软件打开文件
          }, 1500)
        } else {
          // 下载失败
          plus.downloader.clear() // 清除下载任务
          uni.showToast({
            title: '文件下载失败',
            icon: 'error',
          })
        }
      },
    )
    dtask.start()
  }

  /**
   * 判断是否图片类型
   */
  isImg() {
    const url = this.url
    return url.substring(url.length - 3) === 'jpg' || url.substring(url.length - 3) === 'png'
  }

  /**
   * 判断是否视频类型
   */
  isVideo() {
    const url = this.url
    return url.substring(url.length - 3) === 'MP4' || url.substring(url.length - 3) === 'mp4'
  }
}
